require 'rubygems'
require 'hpricot'
require 'open-uri'
class ProductsController < ApplicationController
  before_filter :load_category,:except=>[:scraper,:search,:test_scraper,:update_sort_order,:edit_price,:create,:update]
  before_filter :check_administrator_role,:except => [:index, :show,:search]
  before_filter :find_cart
  # GET /products
  # GET /products.xml
  def index
    @products = Product.paginate :page => params[:page],:per_page => 6

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @products.to_xml(:skip_types => true,:dasherize => false,
          :except => [:active,:created_at,:updated_at]
        )}
    end
  end

  # GET /products/1
  # GET /products/1.xml
  def show
    @product = @category.products.find_by_uuid(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @product }
    end
  end

  # GET /products/new
  # GET /products/new.xml
  def new
    @product = @category.products.build

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @product }
    end
  end

  # GET /products/1/edit
  def edit
    @product = @category.products.find(params[:id])
  end

  # POST /products
  # POST /products.xml
  def create
    @current_category = Category.find(params[:product][:category_id])
    @product = @current_category.products.build(params[:product])

    respond_to do |format|
      if @product.save
        flash[:notice] = 'Product was successfully created.'
        format.html { redirect_to(url_for(:action=>'edit_properties',:id=>@product.id,:category_id=>@current_category.id)) }
        format.xml  { render :xml => @product, :status => :created, :location => @product }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /products/1
  # PUT /products/1.xml
  def update
    @product = Product.find(params[:id])
    old_category_id = @product.category_id
    result = @product.update_attributes(params[:product])
    #维持计数器
    Product.maintain(@product.category_id,old_category_id) if result && @product.category_id != old_category_id

    unless request.xhr?
      respond_to do |format|
        if result
          flash[:notice] = 'Product was successfully updated.'
          format.html { redirect_to("/categories/#{@product.category_id}/products/#{@product.uuid}") }
          format.xml  { head :ok }
        else
          format.html { render :action => "edit" }
          format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
        end
      end
    else
      if result
        render :text=>params[:product].values[0]
      else
        render :text=>'更新失败'
      end
    end
  end

  # DELETE /products/1
  # DELETE /products/1.xml
  def destroy
    @product = @category.products.find(params[:id])
    @product.destroy

    respond_to do |format|
      format.html { redirect_to(@category) }
      format.xml  { head :ok }
    end
  end

  def edit_properties
    product = @category.products.find(params[:id])
    if product.category
      @properties = product.category.properties
    else
      flash[:notice] = '请为商品选择类别.'
    end
  end

  def edit_price
    if params[:brand_id] && params[:category_id] && params[:brand_id] != "0" && params[:category_id] !="0"
      conditions = ["brand_id = ? and category_id = ?",params[:brand_id],params[:category_id]]
    elsif params[:brand_id]!= "0"
      conditions = ["brand_id = ?",params[:brand_id]]
    elsif params[:category_id]!="0"
      conditions = ["category_id = ?",params[:category_id]]
    end

    @products = Product.find(:all,
      :conditions=>conditions) if conditions
  end

  def update_properties
    @product = @category.products.find(params[:id])

    if params[:property]
      respond_to do |format|
        if Hold.create(params[:property].values)
          flash[:notice] = 'Product was successfully updated.'
          format.html { redirect_to(@product) }
          format.xml  { head :ok }
        else
          format.html { render :action => "edit" }
          format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
        end
      end
    end
  end

  def scraper
    if params[:site]
      count = Product.scraper(params[:site],params[:category_id],params[:brand_id],params[:object_type])
      respond_to do |format|
        if count > 0
          flash[:notice] = "#{count} products was successfully created."
          format.html { redirect_to("/store") }
          #          format.xml  { head :ok }
        else
          format.html { render :action => "scraper" }
          #          format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
        end
      end
    end
  end

  def test_scraper
    if !params[:site].blank? && !params[:xpath].blank?
      doc = open(params[:site]){ |f| Hpricot(f)}
      iconv=Iconv.new("UTF-8//IGNORE","utf8")
      @result =  iconv.iconv(doc.search(params[:xpath]).to_html)
    end

    if !params[:regex].blank? && !params[:content].blank?
      doc = Hpricot(params[:content])
      @reg_result  = doc.inner_text.scan(Regexp.new(params[:regex])).join(",")
    end
  end

  def search
    if params[:keyword]
      @products = Product.paginate :include=>:brand,
        :conditions=>['products.name like ? or model like ? or products.description like ? or brands.name like ?',
        "%#{params[:keyword]}%","%#{params[:keyword]}%","%#{params[:keyword]}%","%#{params[:keyword]}%"],
        :page => params[:page],:per_page => 5
      respond_to do |format|
        format.html  # search.html.erb
        format.xml  { render :xml => @products }
      end
    end
  end

  def update_sort_order
    json_data =JSON::parse(params[:json])
    json_data.each {|i| Product.update(i["id"],:sort_order=>i["order"])}
    render :text => "true"
  end

  private

  def load_category
    @category = Category.find(params[:category_id])
  end

end
